<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { Search, Calendar, Clock, Message } from '@element-plus/icons-vue'
import { getUserAppointments, cancelAppointment } from '@/apis/user/userAppointmentAPI'
import type { Request, AppointmentVO, PageResponse } from '@/apis/user/userAppointmentAPI'
import { readAllMessages, readSingleMessage } from '@/apis/messageAPI'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { useAppointmentStore } from '@/stores/appointment'

// 用户信息
const authStore = useAuthStore()
const userId = String(authStore.userInfo.id || '')

// 获取预约筛选状态store
const appointmentStore = useAppointmentStore()

// 搜索表单
const searchForm = reactive<Request>({
  userId: userId,
  pageNum: '1',
  pageSize: '10',
  name: appointmentStore.filterName,
  startDate: appointmentStore.filterStartDate,
  endDate: appointmentStore.filterEndDate,
  status: appointmentStore.filterStatus
})

// 预约状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '待处理', value: 'PENDING' },
  { label: '就诊中', value: 'ACCEPTED' },
  { label: '已拒绝', value: 'REJECTED' },
  { label: '已超时', value: 'TIMEOUT' },
  { label: '已完成', value: 'COMPLETED' }
]

// 预约列表数据
const appointmentList = ref<AppointmentVO[]>([])
const total = ref(0)
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)

// 获取预约列表
const getAppointmentList = async () => {
  if (!userId) {
    ElMessage.error('用户未登录')
    return
  }

  loading.value = true
  try {
    searchForm.pageNum = currentPage.value.toString()
    searchForm.pageSize = pageSize.value.toString()

    const res = await getUserAppointments(searchForm)
    console.log('API响应数据:', res)
    if (res.status === 200) {
      // 检查data是否存在
      if (res.data) {
        const data = res.data as PageResponse
        console.log('分页数据:', data)
        // 检查records是否存在且为数组
        if (data.records && Array.isArray(data.records)) {
          // 将API返回的数据映射到组件期望的格式
          appointmentList.value = data.records.map(item => ({
            id: item.id || 0,
            doctorName: item.name || '',
            patientName: item.patientName || '',
            age: item.age || 0,
            gender: item.gender || '',
            avatar: item.avatar || '',
            department: item.department || '未知科室',
            appointmentTime: item.expireTime || item.createTime || '',
            status: item.status || '',
            description: `预约创建于: ${item.createTime || '未知时间'}` || '',
            isRead: item.isRead || false
          }))
          total.value = data.total || 0
        } else {
          console.error('API返回的records不是数组或不存在:', data)
          ElMessage.error('获取预约列表失败: 数据结构不符合预期')
          appointmentList.value = []
          total.value = 0
        }
      } else {
        console.error('API返回的data为空:', res)
        ElMessage.error('获取预约列表失败: 返回数据为空')
        appointmentList.value = []
        total.value = 0
      }
    } else {
      ElMessage.error(res.message || '获取预约列表失败')
    }
  } catch (error) {
    console.error('获取预约列表出错:', error)
    ElMessage.error('获取预约列表出错')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  // 保存筛选条件到store
  appointmentStore.setAllFilters({
    name: searchForm.name,
    status: searchForm.status,
    startDate: searchForm.startDate,
    endDate: searchForm.endDate
  })
  getAppointmentList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.startDate = ''
  searchForm.endDate = ''
  searchForm.status = ''
  currentPage.value = 1
  // 清除store中的筛选条件
  appointmentStore.clearAllFilters()
  getAppointmentList()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getAppointmentList()
}

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  getAppointmentList()
}

// 取消预约
const handleCancelAppointment = (id: number) => {
  ElMessageBox.confirm('确定要取消该预约吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await cancelAppointment(id)
      if (res.code === 200) {
        ElMessage.success('取消预约成功')
        getAppointmentList()
      } else {
        ElMessage.error(res.message || '取消预约失败')
      }
    } catch (error) {
      console.error('取消预约出错:', error)
      ElMessage.error('取消预约出错')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 标记所有消息为已读
const handleReadAllMessages = async () => {
  try {
    const res = await readAllMessages()
    if (res.status === 200) {
      ElMessage.success('已将所有消息标记为已读')
      // 更新UI状态，将所有预约的消息状态更新为已读
      appointmentList.value = appointmentList.value.map(item => ({
        ...item,
        isRead: true
      }))
      // 重新获取预约列表以刷新状态
      getAppointmentList()
    } else {
      ElMessage.error(res.message || '标记所有消息已读失败')
    }
  } catch (error) {
    console.error('标记所有消息已读出错:', error)
    ElMessage.error('标记所有消息已读出错')
  }
}

// 标记单个消息为已读
const handleReadSingleMessage = async (msgId: number) => {
  try {
    const res = await readSingleMessage(msgId)
    if (res.status === 200) {
      ElMessage.success('已标记消息为已读')
      // 更新UI状态，将该预约的消息状态更新为已读
      const index = appointmentList.value.findIndex(item => item.id === msgId)
      if (index !== -1) {
        appointmentList.value[index].isRead = true
      }
      // 重新获取预约列表以刷新状态
      getAppointmentList()
    } else {
      ElMessage.error(res.message || '标记消息已读失败')
    }
  } catch (error) {
    console.error('标记消息已读出错:', error)
    ElMessage.error('标记消息已读出错')
  }
}

// 获取状态标签类型
const getStatusType = (status: string) => {
  switch (status) {
    case 'PENDING':
      return 'warning'
    case 'ACCEPTED':
      return 'primary'
    case 'REJECTED':
      return 'danger'
    case 'TIMEOUT':
      return 'info'
    case 'COMPLETED':
      return 'success'
    default:
      return 'info'
  }
}

// 获取状态显示文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'PENDING':
      return '待处理'
    case 'ACCEPTED':
      return '就诊中'
    case 'REJECTED':
      return '已拒绝'
    case 'TIMEOUT':
      return '已超时'
    case 'COMPLETED':
      return '已完成'
    default:
      return '未知状态'
  }
}

// 监听筛选条件变化
watch(
  () => [searchForm.status, searchForm.name, searchForm.startDate, searchForm.endDate],
  ([status, name, startDate, endDate]) => {
    // 当筛选条件变化时，更新store中的状态
    appointmentStore.setAllFilters({
      status: status as string,
      name: name as string,
      startDate: startDate as string,
      endDate: endDate as string
    })
  }
)

// 页面加载时获取预约列表
onMounted(() => {
  // 从store中恢复筛选条件
  searchForm.name = appointmentStore.filterName
  searchForm.status = appointmentStore.filterStatus
  searchForm.startDate = appointmentStore.filterStartDate
  searchForm.endDate = appointmentStore.filterEndDate

  getAppointmentList()
})
</script>

<template>
  <div class="appointment-container">
    <div class="page-header">
      <h2>我的预约</h2>
      <p>查看和管理您的所有预约记录</p>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="医生姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入医生姓名"
            clearable
            :prefix-icon="Search"
          />
        </el-form-item>
        <el-form-item label="预约日期">
          <el-date-picker
            v-model="searchForm.startDate"
            type="date"
            placeholder="开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :prefix-icon="Calendar"
          />
          <span class="date-separator">至</span>
          <el-date-picker
            v-model="searchForm.endDate"
            type="date"
            placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :prefix-icon="Calendar"
          />
        </el-form-item>
        <el-form-item label="预约状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 预约列表 -->
    <el-card class="list-card">
      <div class="card-header">
        <div class="card-title">预约列表</div>
        <el-button
          type="primary"
          plain
          :icon="Message"
          @click="handleReadAllMessages"
        >
          标记所有消息已读
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="appointmentList"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="doctorName" label="医生姓名" width="120">
          <template #default="{ row }">
            <div class="doctor-info">
              <el-avatar
                :size="30"
                :src="row.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
              />
              <span>{{ row.doctorName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="department" label="科室" width="120" />
        <el-table-column prop="appointmentTime" label="预约时间" width="180">
          <template #default="{ row }">
            <div class="time-info">
              <el-icon><Clock /></el-icon>
              <span>{{ row.appointmentTime }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <div class="status-container">
              <el-tag :type="getStatusType(row.status)" effect="light">
                {{ getStatusText(row.status) }}
              </el-tag>
              <div v-if="!row.isRead" class="unread-indicator"></div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="预约描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'PENDING'"
              type="danger"
              size="small"
              @click="handleCancelAppointment(row.id)"
            >
              取消预约
            </el-button>
            <el-button
              v-if="row.status === 'ACCEPTED'"
              type="primary"
              size="small"
              link
            >
              进入问诊
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
            >
              查看详情
            </el-button>
            <el-button
              v-if="!row.isRead"
              type="info"
              size="small"
              link
              :icon="Message"
              @click="handleReadSingleMessage(row.id)"
            >
              标记已读
            </el-button>
            <el-tag v-else size="small" type="success" effect="plain">已读</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.appointment-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 8px;
}

.page-header p {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.date-separator {
  margin: 0 5px;
}

.doctor-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.time-info {
  display: flex;
  align-items: center;
  gap: 5px;
}

.status-container {
  position: relative;
  display: inline-flex;
  align-items: center;
}

.unread-indicator {
  position: absolute;
  top: -5px;
  right: -5px;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #f56c6c;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
